import _ from 'lodash'
import externalip from 'externalip';
import logger, { info } from './logger';
export const urlEncode = (obj, noEncode = false, widthOutQuery = false) => {
    var ret = [];
    function toQueryPair(key, value) {
        if (typeof value == 'undefined') {
            return key;
        }
        if (noEncode) {
            return key + '=' + (value === null ? '' : String(value));
        }
        return key + '=' + encodeURIComponent(value === null ? '' : String(value));
    }
    for (var key in obj) {
        key = noEncode ? encodeURIComponent(key) : key;
        var values = obj[key];
        if (values && values.constructor == Array) {//数组 
            var queryValues = [];
            for (var i = 0, len = values.length, value; i < len; i++) {
                value = values[i];
                queryValues.push(toQueryPair(key, value));
            }
            ret = ret.concat(queryValues);
        } else { //字符串 
            ret.push(toQueryPair(key, values));
        }
    }
    if (widthOutQuery) {
        return ret.join('&');
    }
    return ret.length ? "?" + ret.join('&') : "";
}

export function randomCode(codeLength) {
    var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');//随机数  
    var code = "";
    for (var i = 0; i < codeLength; i++) {//循环操作  
        var index = Math.floor(Math.random() * 36);//取得随机数的索引（0~35）  
        code += random[index];//根据索引取得随机数加到code上  
    }
    return code;
}

export function excludeEmpty(obj, model) {
    const attrs = Object.keys(model.attributes);
    const newObj = Object.create(null);
    for (let key in obj) {
        if ((!_.isEmpty(obj[key]) || _.isInteger(obj[key])) && attrs.indexOf(key) !== -1) {
            newObj[key] = obj[key];
        }
    }
    return newObj;
}
/**
 * 微信支付使用，先把对象按键排序后转成url参数
 * @param {*} obj 
 */
export function ASCIISortToString(obj) {
    const sortedArr = Object.keys(obj).sort((pre, cur) => {
        return pre > cur ? 1 : -1
    });
    const newObj = {};
    for (let index = 0; index < sortedArr.length; index++) {
        const key = sortedArr[index];
        newObj[key] = obj[key];
    }
    return newObj;
}

export function getClientIP() {
    return new Promise(function (resolve, reject) {
        externalip(function (err, ip) {
            err ? reject(err) : resolve(ip);
        })
    })
}